import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import qs from 'qs'
import {sessionSet,sessionGet,sessionTokenSet,sessionTokenGet} from "@/utils/SessionUtils";

//测试一下
Vue.use(ElementUI);

Vue.config.productionTip = false
axios.defaults.withCredentials=true
//设置相应拦截器
axios.interceptors.response.use(function(response){
  let result = response.data;
  if(result.responseCode === 704){
      console.log("704")
    localStorage.setItem("token", null);
    router.push('/index');
  }
  if(result.responseCode === 201){
      console.log(response)
    let authorization = response.headers.authorization;

    let token = authorization.replace("Bearer ","");
    console.log(token);
    localStorage.setItem("token", token);
  }
  return response;
},function(error){
  console.log('相应错误');
  return Promise.reject(error);
})
axios.interceptors.request.use(
    config =>{
      let token = localStorage.getItem("token")
      // console.log("请求token" + token)
      if(token){
        //这里面获取的请求头的键(tokenHeader)根据每个后端的习惯封装的名称各不相同
        config.headers.Authorization  = token
      }
      return config
    }, error =>{
      return Promise.reject(error)
    }
)

axios.defaults.baseURL = "http://localhost:8099/";
Vue.prototype.$axios = axios;
Vue.prototype.$qs = qs;
Vue.prototype.$sessionSet = sessionSet;
Vue.prototype.$sessionGet = sessionGet;


router.beforeEach(function(to, from, next) {
    let user = sessionGet();
    //除了登陆、注册、首页、商家列表、商家信息之外，都需要判断是否登陆了
    if (!(to.path == '/' || to.path == '/index' || to.path == 'mana' )) {
        if (user == null) {
            router.push('/index');
            location.reload();
        }
    }
    next();
});


new Vue({
  router,
  render: h => h(App)
}).$mount('#app')
